package com.xunfang.service;

import com.xunfang.bean.Student;
import com.xunfang.dao.StudentDao;
import com.xunfang.utils.PageResult;
import com.xunfang.utils.PagingQueryBean;

import java.util.List;

/**
 * @Author lss
 * @CreateTime 2024/6/11
 * @Description
 */
public class StudentService {

    private StudentDao studentDao = new StudentDao();

    public PageResult<Student> pageQuery(String currentPage,String ps) {
        //查询总条数
        int totalSize = studentDao.queryTotalSize();
        //总条数为0直接返回null
        if (totalSize == 0) {
            return null;
        }
        //定义每页显示的条数
        int pageSize = Integer.parseInt(ps);
        //获取总页数
        int totalPage = getTotalPage(totalSize,pageSize);
        //获取当前页
        int cp = formatCurrentPage(currentPage,totalPage);
        //封装分页工具类
        PagingQueryBean pagingQueryBean = new PagingQueryBean(pageSize,cp,totalSize);
        //调用dao查询数据
        //select * from student limit ?,?
        List<Student> studentList = studentDao.pageQuery(pagingQueryBean);

        //把studentList和pagingQueryBean封装到PageResult对象中
        PageResult<Student> pageResult = new PageResult<>();
        pageResult.setDataList(studentList);
        pageResult.setTotalSize(pagingQueryBean.getTotalSize());
        return pageResult;

    }


    //获取总页数
    private int getTotalPage(int totalSize,int pageSize) {
        int totalPage = totalSize / pageSize + (totalSize % pageSize == 0 ? 0 : 1);
        return totalPage;
    }

    //获取当前页
    private int formatCurrentPage(String currentPage,int totalPage) {
        int cp = 1;
        //如果当前页不为空
        if(currentPage != null || currentPage.length() > 0) {
            //把currentPage转成int类型
            try {
                //如果当前页不是数字，会出现转换异常，捕获掉
                cp = Integer.parseInt(currentPage);
            }catch (NumberFormatException e) {
                e.printStackTrace();
            }

        }
        //如果当前页是负数
        if (cp <= 0) {
            cp = 1;
        }
        //如果当前页是>总页数  变成最后一页
        if (cp > totalPage) {
            cp = totalPage;
        }

        return cp;
    }
}
